import { colourBlend, random } from "../../utils/index"

let rad = 0.5;
function createPreviewPx(px, main) {
  if (!px) return [];
  const {size, height} = main;
  let pxs = [];
  let _size = +size + 2;
  let n = ~~(_size / 2);
  let index = main.pxMap.findIndex(
    (p) => px.x == p.x && px.y == p.y
  );
  for (let i = -n; i < n + (_size % 2); i++) {
    for (let j = -n; j < n + (_size % 2); j++) {
      let v = _size % 2 ? 0 : 1;
      let _index = index + height * (i + v) + j + v;
      let p = main.pxMap[_index];
      if (p && _index != index && p.y >= (px.y - n) && p.y <= (px.y + n)) {
        pxs.push(p);
      }
    }
  }
  return [px, ...pxs];
}


export default function (pxs, main) {
  if (pxs.length == 0) return;
  let _graphics = main.previewContainer.children[0];
  let _pxs = createPreviewPx(pxs[0], main);
  _pxs.forEach(px => {
    const {x, y} = px;
    _graphics.beginFill(0x000000, .5);
    _graphics.drawRect(x, y, 1, 1);
    _graphics.endFill();
  })

  if (!main.isUp && main.eventName == "pointerMove" || main.eventName == "pointerDown") {
    main.pxMap.forEach(px => {
      if (Math.random() < rad) {
        let p = _pxs.find(p => p.x == px.x && p.y == px.y);
        if (p) {
          px.color = colourBlend(px.color || "0xFFFFFF", main.pointColor, (px.alpha + random(.5,1)) / 2);
          px.alpha = 1;
        }
      }
    })
    main.drawGraphics();
  }
}